import React, { useState, useEffect } from 'react';
import { 
  Input, 
  Button, 
  Table, 
  Space, 
  Tag, 
  message,
  Card,
  Row,
  Col,
  Modal,
  Radio,
  Pagination,
  Select
} from 'antd';
import { 
  SearchOutlined, 
  SendOutlined, 
  CloseOutlined,
  RollbackOutlined,
  CheckOutlined
} from '@ant-design/icons';
import { getOrderList, cancelOrder, shipOrder, updateOrderStatus, updateOrderTracking, verifyOrder, batchUpdateTracking } from '../../api/shop';
import type { ColumnsType } from 'antd/es/table';


// 订单商品项类型
interface OrderItemType {
  id: number;
  order_id: number;
  product_id: number;
  sku_id: number;
  product_name: string;
  sku_spec: string;
  goods_image: string;
  purchase_num: number;
  unit_price: number;
  item_amount: number;
  discount_amount: number;
  actual_pay_amount: number;
  item_status: number;
  tracking_number: string;
  express_company: string;
  created_at: string;
}

// 订单数据类型
interface OrderType {
  id: number;
  order_no: string;
  order_status: number;
  pay_status: number;
  ship_status: number;
  total_amount: number;
  freight_amount: number;
  discount_amount: number;
  pay_time: string;
  receiver_name: string;
  receiver_phone: string;
  receiving_province: string;
  receiving_city: string;
  receiving_district: string;
  receiving_detail_addr: string;
  rating: string;
  remark: string;
  commission: number;
  commission_settled: number;
  store_id: number;
  proxy_store_id: number;
  description: string;
  sales_type: number;
  delivery_remark: string;
  verification_location: string;
  verification_time: string;
  verification_code: string;
  verification_remark: string;
  cancel_reason: string;
  status_remark: string;
  order_items: OrderItemType[];
  created_at: string;
  updated_at: string;
}

// 分页数据类型
interface PaginationType {
  current_page: number;
  page_size: number;
  total: number;
  total_pages: number;
  has_prev: boolean;
  has_next: boolean;
  prev_page: number;
  next_page: number;
}

const Order: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [orderStatus, setOrderStatus] = useState<number | undefined>(undefined);
  const [payStatus, setPayStatus] = useState<number | undefined>(undefined);
  const [shipStatus, setShipStatus] = useState<number | undefined>(undefined);
  const [salesType, setSalesType] = useState<number | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const [orderList, setOrderList] = useState<OrderType[]>([]);
  const [pagination, setPagination] = useState<PaginationType>({
    current_page: 1,
    page_size: 10,
    total: 0,
    total_pages: 0,
    has_prev: false,
    has_next: false,
    prev_page: 0,
    next_page: 0
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<OrderType | null>(null);
  const [trackingNumber, setTrackingNumber] = useState('');
  const [isCancelModalVisible, setIsCancelModalVisible] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [deliveryRemark, setDeliveryRemark] = useState('');
  const [isStatusModalVisible, setIsStatusModalVisible] = useState(false);
  const [statusRemark, setStatusRemark] = useState('');
  const [newOrderStatus, setNewOrderStatus] = useState<number>(4);
  const [expressCompany, setExpressCompany] = useState('');
  const [isVerifyModalVisible, setIsVerifyModalVisible] = useState(false);
  const [verificationLocation, setVerificationLocation] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [verificationRemark, setVerificationRemark] = useState('');
  const [isBatchTrackingModalVisible, setIsBatchTrackingModalVisible] = useState(false);
  const [batchTrackingData, setBatchTrackingData] = useState('');

  // 获取订单列表
  const fetchOrderList = async (page: number = 1, keyword: string = '', order_status?: number, pay_status?: number, ship_status?: number, sales_type?: number) => {
    setLoading(true);
    try {
      const params: any = {
        page,
        page_size: pagination.page_size,
        keyword
      };
      
      if (order_status !== undefined) params.order_status = order_status;
      if (pay_status !== undefined) params.pay_status = pay_status;
      if (ship_status !== undefined) params.ship_status = ship_status;
      if (sales_type !== undefined) params.sales_type = sales_type;
      
      console.log('订单列表请求参数:', params);
      const response = await getOrderList(params);
      
      console.log('订单列表响应:', response);
      
      if (response) {
        setOrderList(response.list);
        setPagination(response.pagination);
      }
    } catch (error) {
      console.error('获取订单列表失败:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchOrderList();
  }, []);

  // 处理搜索
  const handleSearch = () => {
    fetchOrderList(1, searchText, orderStatus, payStatus, shipStatus, salesType);
  };

  // 处理状态筛选
  const handleStatusFilter = (status: number | undefined, type: 'order' | 'pay' | 'ship' | 'sales') => {
    switch (type) {
      case 'order':
        setOrderStatus(status);
        fetchOrderList(1, searchText, status, payStatus, shipStatus, salesType);
        break;
      case 'pay':
        setPayStatus(status);
        fetchOrderList(1, searchText, orderStatus, status, shipStatus, salesType);
        break;
      case 'ship':
        setShipStatus(status);
        fetchOrderList(1, searchText, orderStatus, payStatus, status, salesType);
        break;
      case 'sales':
        setSalesType(status);
        fetchOrderList(1, searchText, orderStatus, payStatus, shipStatus, status);
        break;
    }
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    const newPageSize = pageSize || pagination.page_size;
    setPagination(prev => ({ ...prev, page_size: newPageSize }));
    fetchOrderList(page, searchText, orderStatus, payStatus, shipStatus, salesType);
  };
  
  // 退货相关状态
  const [isReturnModalVisible, setIsReturnModalVisible] = useState(false);
  const [returnType, setReturnType] = useState<'return_refund' | 'refund_only'>('return_refund');
  const [returnTrackingNumber, setReturnTrackingNumber] = useState('');
  


  // 处理批量发货
  const handleBatchDelivery = () => {
    message.info('批量发货功能暂未实现，请使用批量录入快递单号功能');
  };

  // 处理发货
  const handleShip = (record: OrderType) => {
    setSelectedOrder(record);
    setIsModalVisible(true);
  };

  // 处理取消订单
  const handleCancel = (record: OrderType) => {
    setSelectedOrder(record);
    setIsCancelModalVisible(true);
  };

  // 确认取消订单
  const handleConfirmCancel = async () => {
    if (!cancelReason.trim()) {
      message.error('请输入取消理由');
      return;
    }

    if (!selectedOrder) return;

    try {
      console.log('取消订单:', selectedOrder.id, cancelReason);
      const response = await cancelOrder(selectedOrder.id, {
        cancel_reason: cancelReason
      });
      console.log('取消订单响应:', response);
      
      message.success('订单取消成功');
      setIsCancelModalVisible(false);
      setCancelReason('');
      setSelectedOrder(null);
      
      // 刷新当前页数据
      fetchOrderList(pagination.current_page, searchText, orderStatus, payStatus, shipStatus, salesType);
    } catch (error) {
      console.error('取消订单失败:', error);
      message.error('取消订单失败，请重试');
    }
  };

  // 确认录入快递单号
  const handleConfirmTracking = async () => {
    if (!trackingNumber.trim()) {
      message.error('请输入快递单号');
      return;
    }
    
    if (!expressCompany.trim()) {
      message.error('请输入快递公司');
      return;
    }

    if (!selectedOrder) return;

    try {
      console.log('更新快递单号:', selectedOrder.id, trackingNumber, expressCompany);
      const response = await updateOrderTracking(selectedOrder.id, {
        tracking_number: trackingNumber,
        express_company: expressCompany
      });
      console.log('更新快递单号响应:', response);
      
      message.success(`快递单号 ${trackingNumber} 录入成功`);
      setIsModalVisible(false);
      setTrackingNumber('');
      setExpressCompany('');
      setSelectedOrder(null);
      
      // 刷新当前页数据
      fetchOrderList(pagination.current_page, searchText, orderStatus, payStatus, shipStatus, salesType);
    } catch (error) {
      console.error('更新快递单号失败:', error);
      message.error('更新快递单号失败，请重试');
    }
  };

  // 立即发货
  const handleShipNow = async () => {
    if (!deliveryRemark.trim()) {
      message.error('请输入发货备注');
      return;
    }

    if (!selectedOrder) return;

    try {
      console.log('立即发货:', selectedOrder.id, deliveryRemark);
      const response = await shipOrder(selectedOrder.id, {
        delivery_remark: deliveryRemark
      });
      console.log('发货响应:', response);
      
      message.success('订单发货成功');
      setIsModalVisible(false);
      setDeliveryRemark('');
      setSelectedOrder(null);
      
      // 刷新当前页数据
      fetchOrderList(pagination.current_page, searchText, orderStatus, payStatus, shipStatus, salesType);
    } catch (error) {
      console.error('发货失败:', error);
      message.error('发货失败，请重试');
    }
  };

  // 更新订单状态
  const handleUpdateStatus = async () => {
    if (!statusRemark.trim()) {
      message.error('请输入状态备注');
      return;
    }

    if (!selectedOrder) return;

    try {
      console.log('更新订单状态:', selectedOrder.id, newOrderStatus, statusRemark);
      const response = await updateOrderStatus(selectedOrder.id, {
        order_status: newOrderStatus,
        status_remark: statusRemark
      });
      console.log('更新状态响应:', response);
      
      message.success('订单状态更新成功');
      setIsStatusModalVisible(false);
      setStatusRemark('');
      setSelectedOrder(null);
      
      // 刷新当前页数据
      fetchOrderList(pagination.current_page, searchText, orderStatus, payStatus, shipStatus, salesType);
    } catch (error) {
      console.error('更新状态失败:', error);
      message.error('更新状态失败，请重试');
    }
  };

  // 获取订单状态文本
  const getOrderStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
      1: '待付款',
      2: '待发货', 
      3: '待收货',
      4: '已完成',
      5: '已取消',
      6: '超时关闭',
      7: '售后中'
    };
    return statusMap[status] || '未知状态';
  };

  // 处理更新订单状态
  const handleUpdateOrderStatus = (record: OrderType) => {
    setSelectedOrder(record);
    setNewOrderStatus(4); // 默认设置为已完成
    setStatusRemark('');
    setIsStatusModalVisible(true);
  };

  // 处理订单核销
  const handleVerifyOrder = (record: OrderType) => {
    setSelectedOrder(record);
    setVerificationLocation('');
    setVerificationCode('');
    setVerificationRemark('');
    setIsVerifyModalVisible(true);
  };

  // 确认订单核销
  const handleConfirmVerify = async () => {
    if (!verificationLocation.trim()) {
      message.error('请输入核销地点');
      return;
    }

    if (!verificationCode.trim()) {
      message.error('请输入核销验证码');
      return;
    }

    if (!verificationRemark.trim()) {
      message.error('请输入核销备注');
      return;
    }

    if (!selectedOrder) return;

    try {
      console.log('订单核销:', selectedOrder.id, verificationLocation, verificationCode, verificationRemark);
      const response = await verifyOrder(selectedOrder.id, {
        verification_location: verificationLocation,
        verification_code: verificationCode,
        verification_remark: verificationRemark
      });
      console.log('订单核销响应:', response);
      
      message.success('订单核销成功');
      setIsVerifyModalVisible(false);
      setVerificationLocation('');
      setVerificationCode('');
      setVerificationRemark('');
      setSelectedOrder(null);
      
      // 刷新当前页数据
      fetchOrderList(pagination.current_page, searchText, orderStatus, payStatus, shipStatus, salesType);
    } catch (error) {
      console.error('订单核销失败:', error);
      message.error('订单核销失败，请重试');
    }
  };

  // 处理批量录入快递单号
  const handleBatchTracking = () => {
    setBatchTrackingData('');
    setIsBatchTrackingModalVisible(true);
  };

  // 确认批量录入快递单号
  const handleConfirmBatchTracking = async () => {
    if (!batchTrackingData.trim()) {
      message.error('请输入批量快递数据');
      return;
    }

    try {
      console.log('批量录入快递单号:', batchTrackingData);
      const response = await batchUpdateTracking({
        tracking_data: batchTrackingData
      });
      console.log('批量录入快递单号响应:', response);
      
      message.success('批量录入快递单号成功');
      setIsBatchTrackingModalVisible(false);
      setBatchTrackingData('');
      
      // 刷新当前页数据
      fetchOrderList(pagination.current_page, searchText, orderStatus, payStatus, shipStatus, salesType);
    } catch (error) {
      console.error('批量录入快递单号失败:', error);
      message.error('批量录入快递单号失败，请重试');
    }
  };

  // 处理退货
  const handleReturn = (record: OrderType) => {
    setSelectedOrder(record);
    setIsReturnModalVisible(true);
  };

  // 确认退货
  const handleConfirmReturn = () => {
    if (returnType === 'return_refund' && !returnTrackingNumber.trim()) {
      message.error('请输入退货快递单号');
      return;
    }
    
    // 模拟API调用
    setLoading(true);
    setTimeout(() => {
      const typeText = returnType === 'return_refund' ? '退货退款' : '仅退款';
      message.success(`${typeText}申请已提交！`);
      setIsReturnModalVisible(false);
      setReturnTrackingNumber('');
      setReturnType('return_refund');
      setSelectedOrder(null);
      setLoading(false);
    }, 1000);
  };



  // 表格列配置
  const columns: ColumnsType<OrderType> = [
    {
      title: '订单编号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 150,
      render: (text, record) => (
        <Space direction="vertical" size="small">
          <span>{text}</span>
          <Space>
            <Tag color={
              record.order_status === 1 ? 'orange' :
              record.order_status === 2 ? 'blue' :
              record.order_status === 3 ? 'green' :
              record.order_status === 4 ? 'green' :
              record.order_status === 5 ? 'red' :
              record.order_status === 6 ? 'red' :
              record.order_status === 7 ? 'purple' : 'default'
            }>
              {record.order_status === 1 ? '待付款' :
               record.order_status === 2 ? '待发货' :
               record.order_status === 3 ? '待收货' :
               record.order_status === 4 ? '已完成' :
               record.order_status === 5 ? '已取消' :
               record.order_status === 6 ? '超时关闭' :
               record.order_status === 7 ? '售后中' : '未知'}
            </Tag>
          </Space>
        </Space>
      ),
    },
    {
      title: '商品信息',
      key: 'products',
      width: 200,
      render: (_, record) => (
        <div>
          {record.order_items.map((item, index) => (
            <div key={index} style={{ marginBottom: index < record.order_items.length - 1 ? 8 : 0 }}>
              <div style={{ fontWeight: 'bold' }}>{item.product_name}</div>
              <div style={{ color: '#666', fontSize: '12px' }}>{item.sku_spec}</div>
              <div style={{ color: '#ff4d4f', fontSize: '12px' }}>
                ¥{(item.unit_price / 100).toFixed(2)} × {item.purchase_num}
              </div>
            </div>
          ))}
        </div>
      ),
    },
    {
      title: '收货人',
      key: 'receiver',
      width: 150,
      render: (_, record) => (
        <div>
          <div>{record.receiver_name}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>{record.receiver_phone}</div>
          <div style={{ color: '#999', fontSize: '12px' }}>
            {record.receiving_province}{record.receiving_city}{record.receiving_district}
          </div>
        </div>
      ),
    },
    {
      title: '订单金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      render: (amount: number) => (
        <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
          ¥{(amount / 100).toFixed(2)}
        </span>
      ),
    },
    {
      title: '支付状态',
      dataIndex: 'pay_status',
      key: 'pay_status',
      width: 100,
      render: (status: number) => (
        <Tag color={
          status === 1 ? 'orange' :
          status === 2 ? 'green' :
          status === 3 ? 'red' :
          status === 4 ? 'blue' :
          status === 5 ? 'purple' : 'default'
        }>
          {status === 1 ? '未支付' :
           status === 2 ? '已支付' :
           status === 3 ? '支付失败' :
           status === 4 ? '退款中' :
           status === 5 ? '已退款' : '未知'}
        </Tag>
      ),
    },
    {
      title: '发货状态',
      dataIndex: 'ship_status',
      key: 'ship_status',
      width: 100,
      render: (status: number) => (
        <Tag color={
          status === 1 ? 'orange' :
          status === 2 ? 'blue' :
          status === 3 ? 'purple' :
          status === 4 ? 'green' :
          status === 5 ? 'red' : 'default'
        }>
          {status === 1 ? '待发货' :
           status === 2 ? '已发货' :
           status === 3 ? '运输中' :
           status === 4 ? '已签收' :
           status === 5 ? '拒收' : '未知'}
        </Tag>
      ),
    },
    {
      title: '销售类型',
      dataIndex: 'sales_type',
      key: 'sales_type',
      width: 80,
      render: (type: number) => (
        <Tag color={type === 1 ? 'green' : 'blue'}>
          {type === 1 ? '直销' : '代理'}
        </Tag>
      ),
    },
    {
      title: '下单时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          {record.order_status === 2 && record.ship_status === 1 && (
            <Button
              type="text"
              icon={<SendOutlined />}
              onClick={() => handleShip(record)}
              title="发货"
              style={{ color: '#1890ff' }}
            />
          )}
          {record.ship_status === 2 && (
            <Button
              type="text"
              icon={<RollbackOutlined />}
              onClick={() => handleReturn(record)}
              title="退货"
              style={{ color: '#fa8c16' }}
            />
          )}
          {record.order_status === 3 && (
            <Button
              type="text"
              icon={<CheckOutlined />}
              onClick={() => handleUpdateOrderStatus(record)}
              title="更新状态"
              style={{ color: '#52c41a' }}
            />
          )}
          {record.order_status === 3 && (
            <Button
              type="text"
              icon={<CheckOutlined />}
              onClick={() => handleVerifyOrder(record)}
              title="订单核销"
              style={{ color: '#1890ff' }}
            />
          )}
          <Button
            type="text"
            icon={<CloseOutlined />}
            onClick={() => handleCancel(record)}
            title="取消"
            style={{ color: '#ff4d4f' }}
          />
        </Space>
      ),
    },
  ];

    return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card style={{ borderRadius: '8px' }}>
        {/* 顶部搜索和按钮区域 */}
        <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
          <Col>
            <Space>
              <span style={{ fontSize: '16px', fontWeight: 'bold' }}>订单列表</span>
              <Input
                placeholder="搜索订单号或商品名称"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 300 }}
                allowClear
                onPressEnter={handleSearch}
              />
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                style={{ borderRadius: '6px' }}
              >
                搜索
              </Button>
            </Space>
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={handleBatchDelivery}
              style={{ borderRadius: '6px', marginRight: '8px' }}
            >
              批量发货
            </Button>
            <Button
              type="default"
              icon={<SendOutlined />}
              onClick={handleBatchTracking}
              style={{ borderRadius: '6px' }}
            >
              批量录入快递单号
            </Button>
          </Col>
        </Row>

        {/* 筛选按钮和日期选择区域 */}
        <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
          <Col>
            <Space>
              <Button
                  type={orderStatus === undefined ? 'primary' : 'default'}
                  onClick={() => handleStatusFilter(undefined, 'order')}
                  style={{ borderRadius: '6px' }}
                >
                全部
              </Button>
              <Button
                type={orderStatus === 2 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(2, 'order')}
                style={{ borderRadius: '6px' }}
              >
                待发货
              </Button>
              <Button
                type={orderStatus === 3 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(3, 'order')}
                style={{ borderRadius: '6px' }}
              >
                待收货
              </Button>
              <Button
                type={orderStatus === 1 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(1, 'order')}
                style={{ borderRadius: '6px' }}
              >
                待付款
              </Button>
              <Button
                type={orderStatus === 4 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(4, 'order')}
                style={{ borderRadius: '6px' }}
              >
                已完成
              </Button>
              <Button
                type={orderStatus === 5 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(5, 'order')}
                style={{ borderRadius: '6px' }}
              >
                已取消
              </Button>
              <Button
                type={orderStatus === 6 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(6, 'order')}
                style={{ borderRadius: '6px' }}
              >
                超时关闭
              </Button>
              <Button
                type={orderStatus === 7 ? 'primary' : 'default'}
                onClick={() => handleStatusFilter(7, 'order')}
                style={{ borderRadius: '6px' }}
              >
                售后中
              </Button>
            </Space>
          </Col>
        </Row>
        {/* 表格区域 */}
        <Table
          columns={columns}
          dataSource={orderList}
          loading={loading}
          pagination={false}
          scroll={{ x: 1200 }}
          rowKey="id"
        />

        {/* 分页组件 */}
        <div style={{ marginTop: '16px', textAlign: 'right' }}>
          <Pagination
            current={pagination.current_page}
            total={pagination.total}
            pageSize={pagination.page_size}
            onChange={handlePageChange}
            onShowSizeChange={handlePageChange}
            pageSizeOptions={['10', '20', '50', '100']}
            showSizeChanger
            showQuickJumper
            showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`}
          />
        </div>
      </Card>

      {/* 发货弹窗 */}
      <Modal
        title="订单发货"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          setTrackingNumber('');
          setDeliveryRemark('');
          setExpressCompany('');
          setSelectedOrder(null);
        }}
        footer={[
          <Button key="cancel" onClick={() => {
            setIsModalVisible(false);
            setTrackingNumber('');
            setDeliveryRemark('');
            setExpressCompany('');
            setSelectedOrder(null);
          }}>
            取消
          </Button>,
          <Button key="ship" type="primary" onClick={handleShipNow}>
            立即发货
          </Button>,
          <Button key="tracking" onClick={handleConfirmTracking}>
            录入快递单号
          </Button>
        ]}
        width={500}
      >
        <div style={{ padding: '20px 0' }}>
          {selectedOrder && (
            <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
                订单编号: {selectedOrder.order_no}
              </div>
              <div style={{ fontSize: '14px', color: '#666' }}>
                订单金额: ¥{(selectedOrder.total_amount / 100).toFixed(2)}
              </div>
            </div>
          )}
          
          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              发货备注 *
            </label>
            <Input.TextArea
              placeholder="请输入发货备注，如：虚拟商品立即发货"
              value={deliveryRemark}
              onChange={(e) => setDeliveryRemark(e.target.value)}
              rows={3}
              maxLength={200}
              showCount
              style={{ width: '100%' }}
            />
          </div>

          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              快递单号（可选）
            </label>
            <Input
              placeholder="请输入快递单号"
              value={trackingNumber}
              onChange={(e) => setTrackingNumber(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>

          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              快递公司（可选）
            </label>
            <Input
              placeholder="请输入快递公司，如：顺丰快递"
              value={expressCompany}
              onChange={(e) => setExpressCompany(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>
        </div>
      </Modal>

      {/* 退货弹窗 */}
      <Modal
        title="退货"
        open={isReturnModalVisible}
        onOk={handleConfirmReturn}
        onCancel={() => {
          setIsReturnModalVisible(false);
          setReturnTrackingNumber('');
          setReturnType('return_refund');
          setSelectedOrder(null);
        }}
        okText="确认"
        cancelText="取消"
        width={500}
      >
        <div style={{ padding: '20px 0' }}>
          {/* 退货类型选择 */}
          <div style={{ marginBottom: '20px' }}>
            <Radio.Group 
              value={returnType} 
              onChange={(e) => setReturnType(e.target.value)}
              style={{ width: '100%' }}
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                <Radio value="return_refund">退货退款</Radio>
                <Radio value="refund_only">仅退款</Radio>
              </Space>
            </Radio.Group>
          </div>

          {/* 退货快递单号 */}
          {returnType === 'return_refund' && (
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                退货快递单号
              </label>
              <Input
                placeholder="请输入退货快递单号"
                value={returnTrackingNumber}
                onChange={(e) => setReturnTrackingNumber(e.target.value)}
                style={{ width: '100%' }}
              />
            </div>
          )}

          {/* 用户申请信息 */}
          <div style={{ marginBottom: '20px' }}>
            <div style={{ fontSize: '14px', color: '#666' }}>
              用户申请信息: 无
            </div>
          </div>

          {/* 订单信息 */}
          {selectedOrder && (
            <div style={{ fontSize: '14px', color: '#666' }}>
              订单编号: {selectedOrder.order_no}
            </div>
          )}
        </div>
      </Modal>


      {/* 取消订单模态框 */}
      <Modal
        title="取消订单"
        open={isCancelModalVisible}
        onOk={handleConfirmCancel}
        onCancel={() => {
          setIsCancelModalVisible(false);
          setCancelReason('');
          setSelectedOrder(null);
        }}
        okText="确认取消"
        cancelText="取消"
        okButtonProps={{ danger: true }}
      >
        <div>
          {selectedOrder && (
            <div style={{ marginBottom: '16px' }}>
              <div style={{ fontSize: '14px', color: '#666', marginBottom: '8px' }}>
                订单编号: {selectedOrder.order_no}
              </div>
              <div style={{ fontSize: '14px', color: '#666' }}>
                订单金额: ¥{(selectedOrder.total_amount / 100).toFixed(2)}
              </div>
            </div>
          )}
          
          <div style={{ marginBottom: '8px' }}>
            <label style={{ fontWeight: 'bold' }}>取消理由 *</label>
          </div>
          <Input.TextArea
            value={cancelReason}
            onChange={(e) => setCancelReason(e.target.value)}
            placeholder="请输入取消理由，如：商品缺货，无法发货"
            rows={4}
            maxLength={200}
            showCount
          />
        </div>
      </Modal>

      {/* 更新订单状态模态框 */}
      <Modal
        title="更新订单状态"
        open={isStatusModalVisible}
        onOk={handleUpdateStatus}
        onCancel={() => {
          setIsStatusModalVisible(false);
          setStatusRemark('');
          setSelectedOrder(null);
        }}
        okText="确认更新"
        cancelText="取消"
        width={500}
      >
        <div>
          {selectedOrder && (
            <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
                订单编号: {selectedOrder.order_no}
              </div>
              <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
                当前状态: {getOrderStatusText(selectedOrder.order_status)}
              </div>
              <div style={{ fontSize: '14px', color: '#666' }}>
                订单金额: ¥{(selectedOrder.total_amount / 100).toFixed(2)}
              </div>
            </div>
          )}
          
          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              新订单状态 *
            </label>
            <Select
              value={newOrderStatus}
              onChange={setNewOrderStatus}
              style={{ width: '100%' }}
            >
              <Select.Option value={1}>待付款</Select.Option>
              <Select.Option value={2}>待发货</Select.Option>
              <Select.Option value={3}>待收货</Select.Option>
              <Select.Option value={4}>已完成</Select.Option>
              <Select.Option value={5}>已取消</Select.Option>
              <Select.Option value={6}>超时关闭</Select.Option>
              <Select.Option value={7}>售后中</Select.Option>
            </Select>
          </div>

          <div style={{ marginBottom: '8px' }}>
            <label style={{ fontWeight: 'bold' }}>状态备注 *</label>
          </div>
          <Input.TextArea
            value={statusRemark}
            onChange={(e) => setStatusRemark(e.target.value)}
            placeholder="请输入状态备注，如：客户已确认收货，订单完成"
            rows={4}
            maxLength={200}
            showCount
          />
        </div>
      </Modal>

      {/* 订单核销模态框 */}
      <Modal
        title="订单核销"
        open={isVerifyModalVisible}
        onOk={handleConfirmVerify}
        onCancel={() => {
          setIsVerifyModalVisible(false);
          setVerificationLocation('');
          setVerificationCode('');
          setVerificationRemark('');
          setSelectedOrder(null);
        }}
        okText="确认核销"
        cancelText="取消"
        width={500}
      >
        <div>
          {selectedOrder && (
            <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
                订单编号: {selectedOrder.order_no}
              </div>
              <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
                订单状态: {getOrderStatusText(selectedOrder.order_status)}
              </div>
              <div style={{ fontSize: '14px', color: '#666' }}>
                订单金额: ¥{(selectedOrder.total_amount / 100).toFixed(2)}
              </div>
            </div>
          )}
          
          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              核销地点 *
            </label>
            <Input
              placeholder="请输入核销地点，如：深圳市南山区科技园店"
              value={verificationLocation}
              onChange={(e) => setVerificationLocation(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>

          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              核销验证码 *
            </label>
            <Input
              placeholder="请输入核销验证码，如：VERIFY123"
              value={verificationCode}
              onChange={(e) => setVerificationCode(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>

          <div style={{ marginBottom: '8px' }}>
            <label style={{ fontWeight: 'bold' }}>核销备注 *</label>
          </div>
          <Input.TextArea
            value={verificationRemark}
            onChange={(e) => setVerificationRemark(e.target.value)}
            placeholder="请输入核销备注，如：客户已到店取货"
            rows={4}
            maxLength={200}
            showCount
          />
        </div>
      </Modal>

      {/* 批量录入快递单号模态框 */}
      <Modal
        title="批量录入快递单号"
        open={isBatchTrackingModalVisible}
        onOk={handleConfirmBatchTracking}
        onCancel={() => {
          setIsBatchTrackingModalVisible(false);
          setBatchTrackingData('');
        }}
        okText="确认录入"
        cancelText="取消"
        width={600}
      >
        <div>
          <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
            <div style={{ fontSize: '14px', color: '#666', marginBottom: '8px' }}>
              <strong>使用说明：</strong>
            </div>
            <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
              1. 每行一个订单，格式：订单号 快递单号
            </div>
            <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
              2. 订单号和快递单号之间用空格分隔
            </div>
            <div style={{ fontSize: '14px', color: '#666' }}>
              3. 示例：ORD202501270001 SF1234567890
            </div>
          </div>
          
          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              批量快递数据 *
            </label>
            <Input.TextArea
              placeholder={`请输入批量快递数据，格式：订单号 快递单号
示例：
ORD202501270001 SF1234567890
ORD202501270002 YTO9876543210
ORD202501270003 JD5555666677`}
              value={batchTrackingData}
              onChange={(e) => setBatchTrackingData(e.target.value)}
              rows={8}
              style={{ width: '100%' }}
            />
          </div>
        </div>
      </Modal>
        </div>
    );
};

export default Order; 